import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import { Modal } from 'antd';

function Dialog({
  title = '', width = 520, onOk = () => { }, onCancel = () => { }, content = '' 
}) {
  const [openDialog, setOpenDialog] = useState(true);

  const unMount = () => {
    ReactDOM.unmountComponentAtNode(document.querySelector('#dialogContent'));
  };

  const okClick = () => {
    setOpenDialog(false);
    onOk();
    unMount();
  };

  const CancelClick = () => {
    setOpenDialog(false);
    onCancel();
    unMount();
  };

  return (
    <Modal
      width={width}
      title={title}
      visible={openDialog}
      onOk={okClick}
      centered
      onCancel={CancelClick}
    >
      {content}
    </Modal>
  );
}

const showDialog = (props) => {
  const {
    type = '', title = '', content, onOk = () => { }, onCancel = () => { } 
  } = props;
  // 需要卸载Dialog
  // 不需要卸载Dialog -> 会出现多个dialog 需要用户依次关闭

  // 不传Info 则为模态框
  const dialogContent = {
    title,
    content,
    onOk() {
      onOk();
    },
    onCancel() {
      onCancel();
    }
  };

  let dialogType = 'modal';

  switch (type) {
    case 'info':
    case 'error':
    case 'warn':
    case 'success':
      dialogType = type;
      break;
    default:
      dialogType = 'modal';
  }

  if (dialogType === 'modal') {
    const Portal = ReactDOM.createPortal(<Dialog {...props} />, document.querySelector('#dialogContent'));
    ReactDOM.render(Portal, document.querySelector('#dialogContent'));
  } else {
    Modal[dialogType](dialogContent);
  }
};

export default showDialog;
